package cn.lecosa.es;

import java.io.IOException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;

public class ElaFactory {
	// private static final ObjectMapper MAPPER = new ObjectMapper();
	static TransportClient client  =EsClient.eSClient(); 

	public static void main(String[] args) throws Exception {
		 deleteIndex("spark1");
//		elasticsearchAdd();
		
//		 index();
		// bulkUpdate();
		// }
		// indexDelete(client,"AWD8pQ1c33MbGS4mRu79");
	}

	public void bulkDelete() throws Exception {
		BulkRequestBuilder bulkRequest = client.prepareBulk();
		bulkRequest.add(client.prepareIndex("twitter", "tweet", "1").setSource(
				XContentFactory.jsonBuilder().startObject()
						.field("user", "kimchy").field("postDate", new Date())
						.field("message", "trying out Elasticsearch")
						.endObject()));
		bulkRequest.add(client.prepareIndex("twitter", "tweet", "2").setSource(
				XContentFactory.jsonBuilder().startObject()
						.field("user", "kimchy").field("postDate", new Date())
						.field("message", "another post").endObject()));
		BulkResponse response = bulkRequest.get();

		// System.out.println(response.getHeaders());
	}

	public static void bulkUpdate() throws IOException, InterruptedException,
			ExecutionException {
		String index = "trails";
		String type = "person-data";
		// String[] includes = new String[] { "gid", "imsi", "collecttime",
		// "gname", "capturetime", "location",
		// "gaddress" };// 显示的字段
		// String[] excludes = new String[] { "source", "attr", "csq", "seq",
		// "imei", "longitude", "latitude", };// 不显示的字段

		// QueryBuilder queryImsi = QueryBuilders.wildcardQuery("idcard", "*" +
		// imsiq + "*");
		QueryBuilder idcard = QueryBuilders.termQuery("idcard",
				"452824193104134438");
		// QueryBuilder queryIdcard = QueryBuilders.wildcardQuery("idcard", "*"
		// + idCard + "*");

		BoolQueryBuilder bq = QueryBuilders.boolQuery().should(idcard);// filter
		// bq.should(queryIdcard);

		// .should(QueryBuilders.termQuery("now_home", "山西省太原市"));

		/*
		 * if (StringUtils.isNotBlank(startTime) &&
		 * StringUtils.isNotBlank(endTime)) {
		 * bq.filter(QueryBuilders.rangeQuery(
		 * "capturetime").gte(DateUtils.getMinutes(startTime))
		 * .lte(DateUtils.getMinutes(endTime))); }
		 */

		SortBuilder sortBuilder = SortBuilders.fieldSort("capturetime").order(
				SortOrder.DESC);

		SearchResponse response = client.prepareSearch(index)
				// .setFetchSource(includes, excludes)
				.setTypes(type)
				// .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
				.setQuery(bq).addSort(sortBuilder).setFrom(0)
				.setSize(2000000000 - 1).execute().actionGet();

		BulkRequestBuilder bulkRequest = client.prepareBulk();
		// System.out.println("============"+response.getHits().getTotalHits());
		for (SearchHit hit : response.getHits().getHits()) {
			String id = hit.getId();
			String imsiJson = hit.getSourceAsString();
			System.out.println(imsiJson);
			// update(hit.getId());
			// bulkRequest.add(client.prepareIndex("trails","person-data",hit.getId()).setSource(jsonBuilder().startObject().field("isrisk",0)));
			// prepareIndex( "trails","person-data",hit.getId()
			bulkRequest.add(client.prepareUpdate(index, type, id).setDoc(
					XContentFactory.jsonBuilder().startObject()
							.field("isrisk", 0).field("isdrug", 0)
							.field("laiyuan", "qingzhou").endObject()));

		}

		// UpdateResponse response = client.update(updateRequest).get();
		BulkResponse res = bulkRequest.get();
		// BulkResponse res = req.execute().actionGet();
	}

 
	public static void update(String id) throws IOException,
			InterruptedException, ExecutionException {
		UpdateResponse res = client.update(
				new UpdateRequest("trails", "person-data", id)
						.doc(XContentFactory.jsonBuilder().startObject()
								.field("isrisk", 1).field("isdrug", 0)
								// .field("imsi", "46001771751084255555")
								.endObject())).get();
		System.out.println(res.getIndex());

	}

	public static void index() {
		Map<String, Object> map = new HashMap<String, Object>();
		Random ran = new Random();
		// map.put("csq", ran.nextInt(100));

		// source:int,gid_address:string,location:string,gid:int,imsi:string,imei:string,:date,imsi_addr:string,csq:int

		// "csq": "17", 信号强度
		// "gid": "109",
		// "imei": "460018537210104",
		// "imsi": "865180022659710",
		// "time": "2017-08-07 15:56:14",
		// "attr": "吉林 四平",
		// "location": [
		// 124.391382,
		// 43.1755247
		// ]

		// map.put("gid_address", "四川");

		map.put("source", "500000");
		map.put("gid", new Integer(1));
		map.put("imei", "321");
		map.put("imsi", "1233");
		// map.put("collect_time", new Date());
		//
		//
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		// SimpleDateFormat simpleDateFormat = new
		// SimpleDateFormat("yyyy-MM-dd");

		map.put("capturetime",
				simpleDateFormat.format(new Date(System.currentTimeMillis())));
		// map.put("host", ran.nextInt(100));

		map.put("attr", "吉林 四平");
		map.put("csq", ran.nextInt(100));
		map.put("location", new String[] { "106.521708", "29.540159" });
		IndexResponse response = client.prepareIndex("imsi4", "imsi-data")
				.setSource(map).get();
		System.out.println(response);
	}

	public static void indexDelete(Client client, String id) {

		DeleteResponse res = null;
		res = client.prepareDelete("imsi4", "imsi-data", id).execute()
				.actionGet();
		// on shutdown
		client.close();
	}

	// 删除索引库

	public static void deleteIndex(String indexName) {

		try {
			if (!isIndexExists(indexName)) {
				System.out.println(indexName + " not exists");
			} else {

				DeleteIndexResponse dResponse = client.admin().indices()
						.prepareDelete(indexName).execute().actionGet();
				if (dResponse.isAcknowledged()) {
					System.out.println("delete index " + indexName
							+ "  successfully!");
				} else {
					System.out.println("Fail to delete index " + indexName);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 判断索引是否存在 传入参数为索引库名称
	public static boolean isIndexExists(String indexName) {
		boolean flag = false;
		try {

			IndicesExistsRequest inExistsRequest = new IndicesExistsRequest(
					indexName);

			IndicesExistsResponse inExistsResponse = client.admin().indices()
					.exists(inExistsRequest).actionGet();

			if (inExistsResponse.isExists()) {
				flag = true;
			} else {
				flag = false;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return flag;
	}

	/**
	 * 测试multi get api 从不同的index, type, 和id中获取
	 */
	public void testMultiGet() {
		MultiGetResponse multiGetResponse = client.prepareMultiGet()
				.add("twitter", "tweet", "1")
				.add("twitter", "tweet", "2", "3", "4")
				.add("anothoer", "type", "foo").get();

		for (MultiGetItemResponse itemResponse : multiGetResponse) {
			GetResponse response = itemResponse.getResponse();
			if (response.isExists()) {
				String sourceAsString = response.getSourceAsString();
				System.out.println(sourceAsString);
			}
		}
	}

	public  static void elasticsearchAdd() {

		try {
			XContentBuilder content = XContentFactory.jsonBuilder()
					.startObject().field("name", "1111") 
					 .field("age",  "1111") 
					 .field("country",  "1111") 
					 .field("date",  "1111")
					 .endObject();
			IndexResponse result = client.prepareIndex("people", "man")
					.setSource(content).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
